'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async register() {
    const { ctx } = this;
    console.log('ctx', ctx.request.body);
    const params = {
      ...ctx.request.body,
    };
    console.log('controller', params);
    const result = await ctx.service.user.createUser(params);
    if (result) {
      ctx.body = {
        status: 200,
        data: result,
      };
    } else {
      ctx.body = {
        status: 500,
        errMsg: '注册失败',
      };
    }
  }
  async login() {
    const { ctx, app } = this;
    const { email, psw } = ctx.request.body;
    const user = await ctx.service.user.getUser(email);
    if (!user) {
      ctx.body = {
        status: 404,
        errMsg: '用户不存在',
      };
    }
    const { password, nickname } = user;
    if (password !== psw) {
      ctx.body = {
        status: 404,
        errMsg: '密码错误',
      };
    }
    const token = app.jwt.sign({
      // eslint-disable-next-line quote-props
      'username': nickname,
    }, app.config.jwt.secret);

    ctx.set({
      // eslint-disable-next-line quote-props
      'authorization': token,
    });
    ctx.body = {
      status: 200,
      code: 0,
      data: {
        msg: '登录成功',
        token,
      },
    };
  }

  // async userInfo() {
  //   const { ctx } = this;
  //   const secret = '123456';
  //   const token = ctx.request.header.authorization;
  //   const decode = ctx.app.jwt.verify(token, secret);
  //   const { username } = decode;
  //   const user = await ctx.service.user.getUserInfo(username);
  //   if (user) {
  //     ctx.body = {
  //       status: 200,
  //       data: {
  //         data: user,
  //       },
  //     };
  //   } else {
  //     ctx.body = {
  //       status: 500,
  //       errMsg: '用户信息不存在',
  //     };
  //   }
  // }
  async userInfo() {
    const { ctx } = this;
    const { email } = ctx.request.body;
    const user = await ctx.service.user.getUser(email);
    if (user) {
      ctx.body = {
        status: 200,
        data: {
          data: user,
        },
      };
    } else {
      ctx.body = {
        status: 500,
        errMsg: '用户信息不存在',
      };
    }
  }
}

module.exports = UserController;
